package com.fc.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fc.dto.RegionDTO;
import com.fc.dto.pageQuery.RegionPageQueryDTO;
import com.fc.entity.Region;
import com.fc.entity.Route;
import com.fc.mapper.RegionMapper;
import com.fc.mapper.RouteMapper;
import com.fc.result.PageResult;
import com.fc.service.IRegionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;

@Service
public class RegionServiceImpl extends ServiceImpl<RegionMapper, Region> implements IRegionService {

    @Autowired
    private RouteMapper routeMapper;

    @Override
    public void saveRegion(RegionDTO regionDTO) {
        Region region = Region.builder()
                .regionName(regionDTO.getRegionName())
                .createTime(LocalDateTime.now())
                .build();
        save(region);
    }

    @Transactional
    @Override
    public void deleteRegion(Long id) {
        //删除该区域下的线路
        QueryWrapper<Route> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("region_id", id);
        routeMapper.delete(queryWrapper);
        removeById(id);//删除区域
    }

    @Override
    public void updateRegion(RegionDTO regionDTO) {
        Region region = Region.builder()
                .id(regionDTO.getId())
                .regionName(regionDTO.getRegionName())
                .build();
        updateById(region);
    }

    @Override
    public PageResult pageRegion(RegionPageQueryDTO regionPageQueryDTO) {
        Page<Region> page = new Page<>(regionPageQueryDTO.getPageNum(), regionPageQueryDTO.getPageSize());
        String regionName = regionPageQueryDTO.getRegionName();
        Page<Region> pageResult = lambdaQuery().like(regionName != null, Region::getRegionName, regionName)
                .page(page);
        return new PageResult(pageResult.getTotal(), pageResult.getRecords());
    }
}
